import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:vehicle_management/config/Config.dart';
import 'package:vehicle_management/utils/TextFieldItem.dart';
import 'package:vehicle_management/public.dart';

class MineScreen extends StatefulWidget {
  String appKey;
  MineScreen(){
  }
  @override
  _MineScreenState createState() => _MineScreenState();
}

class _MineScreenState extends State<MineScreen> {
  //焦点
  FocusNode _focusNodePassWord = new FocusNode();
  FocusNode _focusNodeNewPassword = new FocusNode();
  FocusNode _focusNodeRePassword = new FocusNode();
  String _appKey;
  _MineScreenState(){
    _appKey = preferences.getString("appKey");
  }
  //用户名输入框控制器，此控制器可以监听用户名输入框操作
  TextEditingController _passwordController = new TextEditingController();
  TextEditingController _rePasswordController = new TextEditingController();
  TextEditingController _newPasswordController = new TextEditingController();

  //表单状态
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

//用户名
  var _password;
  var _newPassword = null;
  var _rePassword = null;
  var _oldShowPwd = false;
  var _newShowPwd = false;
  var _rePsdShowPwd = false;//是否显示密码
//是否显示输入框尾部的清除按钮
  /// 验证用户名

  String validatePassord(value) {
    if (value.isEmpty) {
      return '旧密码不能为空!';
    }
    return null;
  }

  String validateNewPassword(value) {
    if (value.isEmpty) {
      return '新密码不能为空!';
    }
    this._newPassword = value;
    return null;
  }

  String validateRePassword(value) {
    if (value.isEmpty) {
      return '请再次输入密码!';
    }else if(this._newPassword != value){
        print(this._newPassword);
        print(value);
        return "两次密码必须输入一致";
    }
    return null;
  }

  @override
  void initState() {
    //设置焦点监听
    _focusNodePassWord.addListener(_focusNodeListener);
    _focusNodeNewPassword.addListener(_focusNodeListener);
    _focusNodeRePassword.addListener(_focusNodeListener);
    super.initState();
  }

  @override
  void dispose() {
    // 移除焦点监听
    _focusNodePassWord.removeListener(_focusNodeListener);
    _focusNodeNewPassword.removeListener(_focusNodeListener);
    _focusNodeRePassword.removeListener(_focusNodeListener);
    _passwordController.dispose();
    _rePasswordController.dispose();
    _newPasswordController.dispose();
    super.dispose();
  }

  // 监听焦点
  Future<Null> _focusNodeListener() async {
    if (_focusNodePassWord.hasFocus) {
      // 取消身份证的焦点状态
      _focusNodeRePassword.unfocus();
      _focusNodeNewPassword.unfocus();
    }
    if (_focusNodeRePassword.hasFocus) {
      // 取消手机框焦点状态
      _focusNodePassWord.unfocus();
      _focusNodeNewPassword.unfocus();
    }
    if (_focusNodeNewPassword.hasFocus) {
      // 取消手机框焦点状态
      _focusNodePassWord.unfocus();
      _focusNodeRePassword.unfocus();
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    // logo 图片区域
    Widget logoImageArea = new Container(
        alignment: Alignment.center,
        // 设置图片为圆形
        child: Text(
          "修改密码",
          style: TextStyle(
              color: Colors.white,
              fontSize: ScreenUtil().setSp(60),
              fontWeight: FontWeight.bold),
        ));

    //输入文本框区域
    Widget inputTextArea = new Container(
      margin: EdgeInsets.only(
          left: ScreenUtil().setWidth(55), right: ScreenUtil().setWidth(55)),
      child: new Form(
        key: _formKey,
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            /// 请输入旧密码
            TextFieldItem(
              focusNode: _focusNodePassWord,
              keyboardType: TextInputType.text,
              labelText: "旧密码",
              hintText: '请输入旧密码',
              prefixIcon: Icon(
                Icons.lock,
                color: Colors.white,
              ),
              suffixIcon: IconButton(
                icon: Icon(
                    (_oldShowPwd) ? Icons.visibility : Icons.visibility_off,
                    color: Colors.red),
                // 点击改变显示或隐藏密码
                onPressed: () {
                  setState(() {
                    _oldShowPwd = !_oldShowPwd;
                  });
                },
              ),
              obscureText: !_oldShowPwd,
              validator: validatePassord,
              //保存数据
              onSaved: (value) {
                _password = value;
              },
            ),
            new SizedBox(
              height: ScreenUtil().setHeight(30),
            ),

            ///请输入新密码
            TextFieldItem(
              controller: _newPasswordController,
              focusNode: _focusNodeNewPassword,
              keyboardType: TextInputType.number,

              labelText: "新密码",
              hintText: '请输入新密码',
              prefixIcon: Icon(
                Icons.lock,
                color: Colors.white,
              ),
              suffixIcon: IconButton(
                icon: Icon(
                    (_newShowPwd) ? Icons.visibility : Icons.visibility_off,
                    color: Colors.red),
                // 点击改变显示或隐藏密码
                onPressed: () {
                  setState(() {
                    _newShowPwd = !_newShowPwd;
                  });
                },
              ),
              obscureText: !_newShowPwd,
              validator: validateNewPassword,
              //保存数据
              onSaved: (value) {
                _newPassword = value;
              },
            ),
            new SizedBox(
              height: ScreenUtil().setHeight(30),
            ),

            /// 请再次输入密码
            TextFieldItem(
              controller: _rePasswordController,
              focusNode: _focusNodeRePassword,
              keyboardType: TextInputType.number,

              labelText: "再次输入新密码",
              hintText: "请再次输入新密码",
              prefixIcon: Icon(
                Icons.lock,
                color: Colors.white,
              ),
              suffixIcon: IconButton(
                icon: Icon(
                    (_rePsdShowPwd) ? Icons.visibility : Icons.visibility_off,
                    color: Colors.red),
                // 点击改变显示或隐藏密码
                onPressed: () {
                  setState(() {
                    _rePsdShowPwd = !_rePsdShowPwd;
                  });
                },
              ),
              obscureText: !_rePsdShowPwd,
              validator: validateRePassword,
              //保存数据
              onSaved: (value) {
                _rePassword = value;
              },
            ),
            new SizedBox(
              height: ScreenUtil().setHeight(30),
            ),
          ],
        ),
      ),
    );

    // 登录按钮区域
    Widget loginButtonArea = new Container(
      margin: EdgeInsets.only(
          left: ScreenUtil().setWidth(55), right: ScreenUtil().setWidth(55)),
      height: 55,
      child: new RaisedButton(
        color: Color(0xffFB5858),
        child: Text(
          "保存",
          style: Theme.of(context).primaryTextTheme.headline,
        ),
        // 设置按钮圆角
        shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(45.0)),
        onPressed: () async {
          //点击登录按钮，解除焦点，回收键盘
          _focusNodeRePassword.unfocus();
          _focusNodePassWord.unfocus();
          _focusNodeNewPassword.unfocus();

          if (_formKey.currentState.validate()) {
            print(_formKey.currentState.validate());
            //只有输入通过验证，才会执行这里
            _formKey.currentState.save();
            //todo 登录操作
            FormData formData = FormData.fromMap({
              "password": _password,
              "newPassword": _rePassword,
            });
            print(_password);
            print(_newPassword);
            var api = '${Config.updatePasswordUrl}' +
                '?appKey=$_appKey';
            print(api);
            var response = await Dio().post(api, data: formData);
            print(response);
            if (response.data["code"] == 0) {
              // Storage.setString('appKey', json.encode(response.data["data"]));
              Fluttertoast.showToast(
                msg: '${response.data["msg"]}',
                toastLength: Toast.LENGTH_SHORT,
                gravity: ToastGravity.CENTER,
              );
              print(json.encode(response.data["data"]));
              Navigator.pushNamed(context,
                  '/'); //使用的是“命名导航路由”，具体去哪个界面，看main.dart 对应routeName（'/Home'）的界面;
            } else {
              Fluttertoast.showToast(
                msg: '${response.data["msg"]}',
                toastLength: Toast.LENGTH_SHORT,
                gravity: ToastGravity.CENTER,
              );
            }
          }
        },
      ),
    );

    return Scaffold(
      appBar: AppBar(
        centerTitle: true, // 标题居中
        title: Text('我的'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.exit_to_app),
            onPressed: () {
              Navigator.pushReplacementNamed(context, '/');
            },
          ),

        ],
      ),

      // 外层添加一个手势，用于点击空白部分，回收键盘
      body: new GestureDetector(
          onTap: () {
            // 点击空白区域，回收键盘
            _focusNodeNewPassword.unfocus();
            _focusNodePassWord.unfocus();
            _focusNodeRePassword.unfocus();
          },
          child: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: NetworkImage(
                      "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1593176274503&di=9003ad102c989708e09a61f62f6c2dfc&imgtype=0&src=http%3A%2F%2Ft9.baidu.com%2Fit%2Fu%3D2313840380%2C776106152%26fm%3D193"),
                  fit: BoxFit.cover

                  ///AssetImage('images/driverBg.png'),
                  ),
            ),
            child: new ListView(
              children: <Widget>[
                new SizedBox(
                  height: ScreenUtil().setHeight(100),
                ),
                logoImageArea,
                new SizedBox(
                  height: ScreenUtil().setHeight(50),
                ),
                inputTextArea,
                new SizedBox(
                  height: ScreenUtil().setHeight(60),
                ),
                loginButtonArea,
              ],
            ),
          )),
    );
  }
}
